package xj.graph2d.command;

import java.awt.geom.Rectangle2D;

import xj.graph2d.DrawShape;
import xj.graph2d.Group;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;
import xj.graph2d.TextShape;

public class RemoveShapeCommand extends AbstractCommand {

  public RemoveShapeCommand(SimpleDrawView view, SimpleDrawDocument doc,
      DrawShape shape) {
    super(view, doc);
    this.shape = shape;
  }

  public void execute() {
    if (shape != null) {
      Rectangle2D r2;

      if (shape instanceof Group && 
	  doc.getGroup() == shape) {
	r2 = shape.getRepaintRect();
	doc.setGroup(null);
	isSelectedGroup = true;
      } else {
	parent = shape.getParent();
	if (parent == null) {
	  doc.remove(shape);
	  r2 = shape.getRepaintRect();
	} else {
	  r2 = parent.getRepaintRect();
	  pos = parent.indexOfShape(shape);
	  if (pos >= 0) {
	    r2 = (Rectangle2D) r2.clone();
	    parent.removeShape(pos);
	    doc.shapeRemoved(shape);
	    if (shape instanceof TextShape) {
	      TextShape text = (TextShape) shape;
	      TextShape nextline = text.getNextLine();
	      if (nextline != null) {
		nextline.setPosition(text.getEnd1(), true);
	      }
	    }
	    parent.doLayout();
	  }
	}
      }
      canvas.repaintRect(r2, true, true);
    }
  }

  public void undo() {
    if (shape != null) {
      DrawShape selected = doc.getSelectedShape();
      doc.setSelectedShape(null);
      canvas.repaintShape(selected);

      if (isSelectedGroup) {
	doc.setGroup((Group) shape);
	canvas.repaintShape(shape);
      } else {
	if (parent == null) {
	  doc.add(shape, true);
	  canvas.repaintShape(shape);
	} else {
	  if (pos == -1) {
	    pos = parent.addShape(shape);
	  } else {
	    parent.insertShapeAt(shape, pos);
	  }
	  if (shape instanceof TextShape) {
	    TextShape text = (TextShape) shape;
	    text.setPosition(text.getEnd1(), true);
	  }
	  doc.shapeAdded(shape);
	  parent.doLayout();
	  canvas.repaintShape(parent);
	}
      }
    }
  }

  protected DrawShape shape;

  protected DrawShape parent = null;

  protected boolean isSelectedGroup = false;

  protected int pos = -1;

}
